package com.itheima.sh.controller;

import com.github.pagehelper.PageHelper;
import com.itheima.sh.mapper.UserMapper;
import com.itheima.sh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/findAll")
    public List<User> findAll() {
        PageHelper.startPage(1,5);//分页
        return userMapper.findAll();
    }
    //查
    @GetMapping("/{id}")
    public User findUser(@PathVariable("id")Integer id){
        return this.userMapper.findUser(id);
    }
    //增
    @PostMapping(produces = "application/json;charset=utf-8")
    public String addUser(@RequestBody User user){
        this.userMapper.addUser(user);
        return "增加成功";
    }
    //改
    @PutMapping(value = "/{id}",produces ="application/json;charset=utf-8")
    public String updateUser(@PathVariable("id")Integer id,@RequestBody User user){
        this.userMapper.updateUser(id,user);
        return "修改成功";
    }
    @DeleteMapping(value = "/{id}",produces ="application/json;charset=utf-8")
        public String deleteUser(@PathVariable("id") Integer id){
            this.userMapper.deleteUser(id);
            return"删除成功";
        }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    }
